package com.example.a_java.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.a_java.dto.LendingApprovalDTO;
import com.example.a_java.entity.LoanDisbursement;
import com.example.a_java.entity.LoanDisbursementApproval;
import com.example.a_java.mapper.LoanDisbursementApprovalMapper;
import com.example.a_java.service.LoanDisbursementApprovalService;
import com.example.a_java.service.LoanDisbursementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 放款审批Service实现�?
 */
@Service
public class LoanDisbursementApprovalServiceImpl extends ServiceImpl<LoanDisbursementApprovalMapper, LoanDisbursementApproval> implements LoanDisbursementApprovalService {

    @Autowired
    private LoanDisbursementService loanDisbursementService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean approve(LendingApprovalDTO approvalDTO, Long userId, String userName, String userRole) {
        // 1. 查询放款记录是否存在
        LoanDisbursement disbursement = loanDisbursementService.getById(approvalDTO.getDisbursementId());
        if (disbursement == null) {
            throw new RuntimeException("放款记录不存在");
        }
        
        // 2. 检查放款状态是否为待审�?
        if (disbursement.getDisburseStatus() != 10) {
            throw new RuntimeException("放款状态不允许审批");
        }
        
        // 3. 创建审批记录
        LoanDisbursementApproval approval = new LoanDisbursementApproval();
        approval.setDisbursementId(approvalDTO.getDisbursementId());
        approval.setApproverId(userId);
        approval.setApproverName(userName);
        approval.setApproverRole(userRole);
        approval.setDecision(approvalDTO.getDecision());
        approval.setComment(approvalDTO.getComment());
        approval.setApprovalTime(LocalDateTime.now());
        
        // 设置批准金额
        if ("1".equals(approvalDTO.getDecision())) {
            // 如果审批通过，且指定了批准金额，则使用批准金�?
            if (approvalDTO.getApprovedAmount() != null && approvalDTO.getApprovedAmount().compareTo(BigDecimal.ZERO) > 0) {
                approval.setApprovedAmount(approvalDTO.getApprovedAmount());
            } else {
                // 否则使用原申请金�?
                approval.setApprovedAmount(disbursement.getAmount());
            }
        }
        
        // 4. 保存审批记录
        boolean saveResult = this.save(approval);
        
        // 5. 更新放款记录状�?
        if (saveResult) {
            LoanDisbursement updateDisbursement = new LoanDisbursement();
            updateDisbursement.setDisbursementId(disbursement.getDisbursementId());
            updateDisbursement.setApproverId(userId);
            updateDisbursement.setApprover(userName);
            updateDisbursement.setApprovalTime(LocalDateTime.now());
            
            if ("1".equals(approvalDTO.getDecision())) {
                // 审批通过，状态改为处理中
                updateDisbursement.setDisburseStatus(20);
                
                // 如果批准金额与原金额不同，更新金�?
                if (approvalDTO.getApprovedAmount() != null && 
                    approvalDTO.getApprovedAmount().compareTo(disbursement.getAmount()) != 0) {
                    updateDisbursement.setAmount(approvalDTO.getApprovedAmount());
                }
            } else {
                // 审批拒绝，状态改为放款失�?
                updateDisbursement.setDisburseStatus(40);
                updateDisbursement.setFailReason(approvalDTO.getComment());
            }
            
            return loanDisbursementService.updateById(updateDisbursement);
        }
        
        return false;
    }

    @Override
    public List<LoanDisbursementApproval> getApprovalHistory(Long disbursementId) {
        LambdaQueryWrapper<LoanDisbursementApproval> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LoanDisbursementApproval::getDisbursementId, disbursementId)
                .orderByDesc(LoanDisbursementApproval::getApprovalTime);
        return this.list(queryWrapper);
    }
} 
